/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.
 
  This example code is in the public domain..
 */

void setup() {
  TCCR1A = 0;
  TCCR1B = 0;
  OCR1AH = 0;
  OCR1AL = 31;
  ICR1 = 1600;
  //OCR1BH = 0;
  //OCR1BL = 255;
  //bitWrite(TCCR1A, WGM10, 1);
  bitWrite(TCCR1A, WGM11, 1);
  bitWrite(TCCR1B, WGM12, 1);
  bitWrite(TCCR1B, WGM13, 1);
  bitWrite(TCCR1A, COM1A1, 1);
  // Div 64
  //bitWrite(TCCR1B, CS10, 1);
  //bitWrite(TCCR1B, CS11, 1);
  //bitWrite(TCCR1B, CS12, 0);
  // Div 8
  bitWrite(TCCR1B, CS10, 0);
  bitWrite(TCCR1B, CS11, 1);
  bitWrite(TCCR1B, CS12, 0);
  pinMode(9,OUTPUT);
  pinMode(13, OUTPUT);
  Serial.begin(9600);
}
int RequestFreq=4;
int OldRequestFreq=4;
void loop() {
  byte ReadChar;
  if (Serial.available()) {
    // read the most recent byte (which will be from 0 to 255):
    ReadChar = Serial.read();
    if (ReadChar == 43) {
      // "+"
      OldRequestFreq = RequestFreq;
      while (OldRequestFreq == RequestFreq){
        ICR1 = ICR1-1;
        if (RequestFreq > 35 ) {
          RequestFreq = int(16000000/8/ICR1);
        } else {
          RequestFreq = int(16000000/64/ICR1);
        }
      }
      Serial.print('+');
    }
    if (ReadChar == 45) {
      // "-"
      OldRequestFreq = RequestFreq;
      while (OldRequestFreq == RequestFreq){
        ICR1 = ICR1+1;
        if (RequestFreq > 35 ) {
          RequestFreq = int(16000000/8/ICR1);
        } else {
          RequestFreq = int(16000000/64/ICR1);
        }
      )
    }
    if (ReadChar == 47) {
      // "/"
      RequestFreq = RequestFreq/2;
    }
    if (ReadChar == 42) {
      // "*"
      RequestFreq = RequestFreq*2;
    }
    Serial.println(RequestFreq);
  }

  if (RequestFreq > 35 ) {
    // Div 8
    bitWrite(TCCR1B, CS10, 0);
    bitWrite(TCCR1B, CS11, 1);
    bitWrite(TCCR1B, CS12, 0);
    OCR1AH = 0;
    OCR1AL = 31;
    ICR1 = int(16000000/8/RequestFreq);
  }
  else {
    // Div 64
    bitWrite(TCCR1B, CS10, 1);
    bitWrite(TCCR1B, CS11, 1);
    bitWrite(TCCR1B, CS12, 0);
    OCR1AH = 0;
    OCR1AL = 3;
    ICR1 = int(16000000/64/RequestFreq);
  }
  
}
